import numpy as np
import torch
import matplotlib.pyplot as plt

xy = np.loadtxt('data/diabetes.csv.gz',delimiter=',',dtype=np.float32)

x_data = torch.from_numpy(xy[:,:-1])
y_data = torch.from_numpy(xy[:,[-1]])

# print(x_data)
# print(y_data)

class Modal(torch.nn.Module):
    def __init__(self):
        super(Modal,self).__init__()
        self.linear1 = torch.nn.Linear(8,6)
        self.linear2 = torch.nn.Linear(6,4)
        self.linear3 = torch.nn.Linear(4,1)
        self.sigmoid = torch.nn.Sigmoid()
        self.relu = torch.nn.ReLU()

    def forward(self,x):
        # 使用sigmoid作为激活函数
        # x = self.sigmoid(self.linear1(x))
        # x = self.sigmoid(self.linear2(x))
        # x = self.sigmoid(self.linear3(x))

        # 使用relu作为激活函数
        # x = self.relu(self.linear1(x))
        # x = self.relu(self.linear2(x))
        # x = self.relu(self.linear3(x))

        x = self.relu(self.linear1(x))
        x = self.relu(self.linear2(x))
        x = self.sigmoid(self.linear3(x))


        return x

modal = Modal()

# 构造损失函数和训练器
criterion = torch.nn.MSELoss(reduction='mean')
optimizer = torch.optim.SGD(modal.parameters(),lr=0.01)

if __name__ == "__main__":

    loss_list = []
    for epoch in range(100):
        y_pred = modal(x_data)
        loss = criterion(y_pred,y_data)
        loss_list.append(loss.item())

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    plt.plot(range(100),loss_list)
    plt.xlabel('epoch')
    plt.ylabel('loss')
    plt.show()
